package com.yanzu.module.member.service.iot;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.yanzu.module.member.dal.dataobject.storeinfo.StoreInfoDO;
import com.yanzu.module.member.dal.mysql.storeinfo.StoreInfoMapper;
import com.yanzu.module.member.forest.TTLockClient;
import com.yanzu.module.member.service.iot.device.IotDeviceSetAutoLockReqVO;
import com.yanzu.module.member.service.iot.ttlockBean.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.yanzu.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yanzu.module.member.enums.ErrorCodeConstants.*;


/**
 * @PACKAGE_NAME: com.yanzu.module.member.service.iot
 * @DESCRIPTION:
 * @USER: MrGuan  mrguan@aliyun.com
 * @DATE: 2024/3/22 13:56
 */
@Slf4j
@Component
public class TTLockService {

    @Resource
    private TTLockClient ttLockClient;

    @Value("${ttlock.clientId}")
    private String clientId;

    @Value("${ttlock.clientSecret}")
    private String clientSecret;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private StoreInfoMapper storeInfoMapper;

    private final String redis_key = "ttlock.token_%s";

    public String getToken(Long storeId) {
        String key = String.format(redis_key, storeId);
        if (stringRedisTemplate.hasKey(key)) {
            return stringRedisTemplate.opsForValue().get(key);
        } else {
            //查出用户名和密码
            StoreInfoDO storeInfoDO = storeInfoMapper.selectById(storeId);
            if (ObjectUtils.isEmpty(storeInfoDO.getTtlockUsername()) || ObjectUtils.isEmpty(storeInfoDO.getTtlockPassword())) {
                throw exception(TTLOCK_USER_NOT_FOUND);
            }
            TTLockTokenReqVO reqVO = new TTLockTokenReqVO();
            reqVO.setClientId(clientId);
            reqVO.setClientSecret(clientSecret);
            reqVO.setUsername(storeInfoDO.getTtlockUsername());
            reqVO.setPassword(SecureUtil.md5(storeInfoDO.getTtlockPassword()));
            JSONObject resp = ttLockClient.getToken(reqVO);
            String accessToken = resp.getString("access_token");
            stringRedisTemplate.opsForValue().set(key, resp.getString("access_token"), resp.getLong("expires_in"), TimeUnit.SECONDS);
            return accessToken;
        }
    }

    public String getKey(Integer lockId, Long storeId) {
        String token = this.getToken(storeId);
        TTLockKeyReqVO reqVO = new TTLockKeyReqVO();
        reqVO.setAccessToken(token);
        reqVO.setLockId(lockId);
        reqVO.setDate(new Date().getTime());
        reqVO.setClientId(clientId);
        JSONObject key = ttLockClient.getKey(reqVO);
        log.info("{}钥匙信息查询结果:{}", lockId, key);
        if (key.containsKey("lockData")) {
            return key.getString("lockData");
        } else {
            throw exception(DEVICE_NOT_FOUND);
        }
    }

    public String lock(Integer lockId, Long storeId) {
        String token = this.getToken(storeId);
//        passage(lockId, 2);
        TTLockKeyReqVO reqVO = new TTLockKeyReqVO();
        reqVO.setAccessToken(token);
        reqVO.setLockId(lockId);
        reqVO.setDate(new Date().getTime());
        reqVO.setClientId(clientId);
        JSONObject resp = ttLockClient.lock(reqVO);
        log.info("网关关锁:{},结果:{}", lockId, resp);
        return resp.getString("errmsg");

    }

    public String unlock(Integer lockId, Long storeId) {
        String token = this.getToken(storeId);
        TTLockKeyReqVO reqVO = new TTLockKeyReqVO();
        reqVO.setAccessToken(token);
        reqVO.setLockId(lockId);
        reqVO.setDate(new Date().getTime());
        reqVO.setClientId(clientId);
        JSONObject resp = ttLockClient.unlock(reqVO);
        log.info("网关开锁:{},结果:{}", lockId, resp);
        return resp.getString("errmsg");
    }


    public void setLockAutoLock(IotDeviceSetAutoLockReqVO reqVO, String lockId, Long storeId) {
        String token = this.getToken(storeId);
        TTLockAutoLockReqVO vo = new TTLockAutoLockReqVO();
        vo.setAccessToken(token);
        vo.setDate(new Date().getTime());
        vo.setClientId(clientId);
        vo.setSeconds(reqVO.getSecend());
        vo.setLockId(Integer.valueOf(lockId));
        JSONObject resp = ttLockClient.setLockAutoLock(vo);
        log.info("修改门锁自动关锁时间设置:{},结果:{}", lockId, resp);
        if (resp.getInteger("errcode") != 0) {
            throw exception(DEVICE_OPTION_ERROR, resp.getString("description"));
        } else {
            //设置成功 触发一下关锁  关锁时
            lock(Integer.valueOf(lockId), storeId);
        }
    }

}
